package xyz.naokeziteng.sort;

import java.util.Random;

/**
 * @author hawk
 * @date 2022/8/18
 * @desc
 **/
public class DualPivotQuicksort {
    public static Random random = new Random();


    public static void quickSort(int[] arr, int l, int r) {
        if (l >= r) {
            return;
        }
        int p = partition(arr, l, r);
        //递归处理
        quickSort(arr, l, p - 1);
        quickSort(arr, p + 1, r);
    }

    //分割数组
    //循环不变量 arr[l+1,i-1] <= v , arr[j+1,r] >= v
    public static int partition(int[] arr, int l, int r) {
        int step = random.nextInt(r - l + 1);
        //参照元素
        swap(arr, l, l + step);
        int v = arr[l];
        int i = l + 1;
        int j = r;
        while (true) {
            while (i <= j && arr[i] < v) {
                i++;
            }
            while (j >= i && arr[j] > v) {
                j--;
            }
            if (i >= j) {
                break;
            }
            swap(arr, i, j);
            i++;
            j--;
        }
        //交换位置j和位置l元素
        swap(arr, l, j);
        return j;
    }

    private static void swap(int[] arr, int i, int j) {
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }

    public static void main(String[] args) {
        int[] arr = {4, 6, 5, 2, 3, 8, 7, 1};
        //merge(arr, 0, 3, 7);
        quickSort(arr, 0, 7);
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}
